package com.smartcloud.scadmin.core.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    // 登录失败，异常抛出
    @Override
    protected boolean onLoginFailure(AuthenticationToken token,
                                     AuthenticationException e, ServletRequest request,
                                     ServletResponse response) {
        String className = e.getClass().getName();
        if (e != null
                && !UnknownAccountException.class.getName().equals(className)
                && !IncorrectCredentialsException.class.getName().equals(
                className)
                && !LockedAccountException.class.getName().equals(className)) { // 用户被锁定
            e.printStackTrace(); // 非验证异常抛出
        }
        return super.onLoginFailure(token, e, request, response);
    }

    // 重写认证通过后的页面跳转，shiro会默认跳转到上一次请求的页面，不适用于iframe的框架
    @Override
    protected void issueSuccessRedirect(ServletRequest request,
                                        ServletResponse response) throws Exception {
        // 认证通过后的跳转地址
        System.out.println("认证通过后的跳转地址"+getSuccessUrl());
        WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request,
                                              ServletResponse response) {
        System.out.println("create Token");
        String username = getUsername(request);
        String password = getPassword(request);
        boolean remberMe = isRememberMe(request);
        String host = "";
        String captcha = "";
        String ipAddr = "";
        return new MyAuthenticationToken(username, password, remberMe, host,
                captcha, ipAddr);
    }
}